package com.nh.utils.http;

import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * @author sean
 * 
 * @since 2009/05/09
 * 
 *        使用HttpClient组件，连接web 查询手机号码归属地 服务器端是由sogou开发的查询模块
 * 
 */
public class SimpleHttpClient {

	static HttpMethod method = null;
	static String reponse = null;
	static String phone; // 需要查询的手机号码

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		phone="15208715340";
		query();
	}

	/**
	 * 进行查询 1. 初始化httpclient对象 2. 设置host, port, protocol 3. 获得postMethod 4.
	 * client.executeMethod()，执行查询工作
	 */
	private static void query() {
		// TODO Auto-generated method stub
		String host = "www.sogou.com";
		// 实例化一个httpClient对象
		HttpClient client = new HttpClient();

		// 设置host, port, protocol
		client.getHostConfiguration().setHost(host, 80, "http");

		method = getPostMethod(phone);

		try {
			client.executeMethod(method);
			System.out.println(method.getStatusLine());

			reponse = method.getResponseBodyAsString();
		} catch (HttpException e) {
			System.out.println("httpexception");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 释放当前连接
		method.releaseConnection();

		// 根据html源码提取需要的手机号码归谁地信息
		if (reponse.contains("手机号")) {
			int beginIndex = reponse.indexOf("手机号：");
			int endIndex = reponse.indexOf("用户");

			reponse = reponse.substring(beginIndex, endIndex);
			reponse = reponse.replace("<p>", "");
			reponse = reponse.replace("</p>", "");
			System.out.println(reponse);
		} else {
			System.out.println("error");
		}

	}

	/**
	 * 使用 POST 方式提交数据 1. 获得post对象，需要设置相对路径作为
	 * 
	 * @return
	 */
	private static HttpMethod getPostMethod(String phone) {
		PostMethod post = new PostMethod("/features/mobile.jsp");

		// 类似hashmap的key, value, 成对保存在simcard中
		NameValuePair simcard = new NameValuePair("query", phone);
		post.setRequestBody(new NameValuePair[] { simcard });
		return post;
	}
}